package com.rednose.videoplayer.activities;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.SearchView;

import com.rednose.videoplayer.model.MediaFiles;
import com.rednose.videoplayer.R;
import com.rednose.videoplayer.adapters.VideoFilesAdapter;

import java.util.ArrayList;


//打开文件夹之后，在这个活动里显示所有的视频文件，点击视频文件后播放视频
public class VideoFilesActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{

    public static final String MY_PREF = "my pref";     //用于存储用户的配置信息
    RecyclerView recyclerView;//用于显示视频文件的RecyclerView
    private ArrayList<MediaFiles> videoFilesArrayList = new ArrayList<>();//存储所有的视频文件的model
    static VideoFilesAdapter videoFilesAdapter;//用于显示视频文件的适配器
    String folder_name;//文件夹的名称
    SwipeRefreshLayout swipeRefreshLayout;//用于刷新
    String sortOrder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_files);
        folder_name = getIntent().getStringExtra("folderName");//获取文件夹的名称，他是从VideoFoldersAdapter传过来的

        getSupportActionBar().setTitle(folder_name);//设置标题为文件夹的名称
        recyclerView = findViewById(R.id.videos_rv);
        swipeRefreshLayout = findViewById(R.id.swipe_refresh_videos);//获取刷新控件

        SharedPreferences.Editor editor = getSharedPreferences(MY_PREF, MODE_PRIVATE).edit();
        editor.putString("playlistFOlderName", folder_name);                                //将文件夹的名称存储到SharedPreferences中
        editor.apply();


        showVideoFiles();

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {        //设置刷新监听器
            @Override
            public void onRefresh() {                                                               //刷新时调用
                showVideoFiles();
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void showVideoFiles() {
        videoFilesArrayList = fetchMedia(folder_name);//获取所有的视频文件
        videoFilesAdapter = new VideoFilesAdapter(videoFilesArrayList, this,0);
        recyclerView.setAdapter(videoFilesAdapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(this, RecyclerView.VERTICAL, false));
        videoFilesAdapter.notifyDataSetChanged();//通知适配器数据已经改变
//        Toast.makeText(this, "Videos loaded successfully.", Toast.LENGTH_SHORT).show();
    }

    @SuppressLint("Range")
    private ArrayList<MediaFiles> fetchMedia(String folderName) {
        SharedPreferences preferences = getSharedPreferences(MY_PREF, MODE_PRIVATE);
        String sort_value = preferences.getString("sort","abcd");               //获取用户的排序方式

        ArrayList<MediaFiles> videoFiles = new ArrayList<>();
        Uri uri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;//获取所有的视频文件的uri

        if (sort_value.equals("sortName")) {                                        //根据用户的排序方式设置排序顺序
            sortOrder = MediaStore.MediaColumns.DISPLAY_NAME+" ASC";
        } else if (sort_value.equals("sortSize")) {
            sortOrder = MediaStore.MediaColumns.SIZE+" DESC";
        } else if (sort_value.equals("sortDate")) {
            sortOrder = MediaStore.MediaColumns.DATE_ADDED + " DESC";
        } else {
            sortOrder = MediaStore.Video.Media.DURATION+" DESC";
        }

        String selection = MediaStore.Video.Media.DATA + " like?";//查询条件：文件路径包含某个文件夹
        String[] selectionArgs = new String[]{"%"+folderName+"%"};


        Cursor cursor = getContentResolver().query(uri, null, selection, selectionArgs, sortOrder);//查询媒体库

        if(cursor != null && cursor.moveToNext()) {
            do {
                String id = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media._ID));
                String title = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.TITLE));
                String displayName = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
                String size = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.SIZE));
                String duration = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DURATION));
                String path = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATA));
                String dateAdded = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Media.DATE_ADDED));
                MediaFiles mediaFiles = new MediaFiles(id, title, displayName, size, duration, path, dateAdded);
                videoFiles.add(mediaFiles);
            } while(cursor.moveToNext());
            cursor.close();
        }
        return videoFiles;
    }

    @Override           //搜索文本提交时调用，用于搜索视频文件，根据标题搜索
    public boolean onCreateOptionsMenu(Menu menu) {                             //创建菜单
        getMenuInflater().inflate(R.menu.video_menu, menu);                     //加载菜单
        MenuItem menuItem = menu.findItem(R.id.search_video);                   //获取搜索菜单项
        SearchView searchView = (SearchView) menuItem.getActionView();          //获取搜索视图
        searchView.setOnQueryTextListener(this);                                //设置搜索监听器
        return super.onCreateOptionsMenu(menu);
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        SharedPreferences preferences = getSharedPreferences(MY_PREF,MODE_PRIVATE);                 //获取用户配置信息
        SharedPreferences.Editor editor = preferences.edit();                                       //获取编辑器

        int id = item.getItemId();                                                                  //获取菜单项的id
        if (id == R.id.refresh_files) {                                                             //如果是刷新菜单项
            finish();
            startActivity(getIntent());
        } else if (id == R.id.sort_by) {                                                            //如果是排序菜单项
            AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
            alertDialog.setTitle("排序方式");
            alertDialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {       //设置确定按钮
                @Override
                public void onClick(DialogInterface dialog, int which) {                            //点击确定按钮时调用
                    editor.apply();                                         //提交编辑器
                    finish();                                               //结束当前活动
                    startActivity(getIntent());                             //重新启动当前活动
                    dialog.dismiss();                                       //关闭对话框
                }
            });
            String[] items = {"按字母排序 (A to Z)", "按大小排序 (Big to Small)", "按日期排序 (New to Old)", "按时长排序 (Long to Short)"};
            alertDialog.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    if (which == 0) {
                        editor.putString("sort", "sortName");
                    } else if (which == 1) {
                        editor.putString("sort", "sortSize");
                    } else if (which == 2) {
                        editor.putString("sort", "sortDate");
                    } else if (which == 3) {
                        editor.putString("sort", "sortLength");
                    }
                }
            });
            alertDialog.create().show();
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }

    @Override     //搜索文本改变时调用，用于搜索视频文件，根据标题搜索
    public boolean onQueryTextChange(String newText) {
        String inputs = newText.toLowerCase();                                  //获取输入的文本
        ArrayList<MediaFiles> mediaFiles = new ArrayList<>();                   //存储搜索结果
        for (MediaFiles media : videoFilesArrayList) {                          //遍历所有的视频文件
            if (media.getTitle().toLowerCase().contains(inputs)) {              //如果视频文件的标题包含输入的文本
                mediaFiles.add(media);
            }
        }
        VideoFilesActivity.videoFilesAdapter.updateVideoFiles(mediaFiles);      //更新视频文件
        return true;                                                            //返回true
    }
}